package com.frx.datastruct.chaptereleven;

/**
 * Created by xurenfeng on 2019/3/14.
 */
public class UnionFind2 implements UF{
    /** 使用一个数组构建一个指向parent的树
     * parent[i] 表示一个元素所指向的父节点
     * */
    private int[] parent;

    public UnionFind2(int size){
        parent = new int[size];

        for (int i = 0;i<size;i++){
            parent[i] = i;
        }
    }


    private int find(int p){

        if (p < 0 || p > parent.length){
            throw  new IllegalArgumentException(" p is out of bound !");
        }
        //根节点的特点，parent[p] = p
        while (p != parent[p]){
            p = parent[p];
        }
        return parent[p];
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {

        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot){
            return;
        }

        parent[pRoot] = qRoot;
    }
}
